package cn.mutsuki.micrometer.controller;

import cn.mutsuki.micrometer.core.MetricTemplate;
import cn.mutsuki.micrometer.service.ExampleService;
import io.micrometer.core.instrument.Meter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@RestController
@RequestMapping("/meter")
public class MeterTest {
    private final MetricTemplate metricTemplate;
    private final ExampleService exampleService;
    private CopyOnWriteArrayList<Integer> randomIntList = new CopyOnWriteArrayList<>();

    @Autowired
    public MeterTest(MetricTemplate metricTemplate , ExampleService exampleService){
        this.metricTemplate = metricTemplate;
        this.exampleService = exampleService;
        //计量器初始化
        this.metricTemplate.gaugeSet("random.list.gauge" , target -> ((List)target).size() , randomIntList);
    }

    /**
     * 每访问一次该页面，green_count计数器+1
     */
    @RequestMapping("/greet")
    public String greet(){
        return "greet count: " + metricTemplate.counterAdd("greet.count");
    }

    /**
     *每访问一次，生成一个随机值，并存入randomIntList
     * @return 返回随机产生的值
     */
    @RequestMapping("/random")
    public int randomNumber(){
        int randomNumber = (int) (Math.random() * 100);
        randomIntList.add(randomNumber);
        return randomNumber;
    }

    /**
     * 访问该页面后会启动一个执行5秒的线程，并用timer计算执行的时间
     */
    @RequestMapping("/timer")
    public void timerTest(){
        Meter.Id meterIdentity = metricTemplate.startTimer("timer.test");
        new Thread(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            metricTemplate.stopTimer(meterIdentity);
        }).start();
    }

    /**
     * 访问该页面后会启动一个执行5秒的线程，并用longTaskTimer计算执行的时间
     * record方法似乎不会去开启一个线程，而是直接调用run方法，故会阻塞
     */
    @RequestMapping("/long-task-timer")
    public void longTaskTimerTest(){
        Runnable runnable = new Thread(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });
        metricTemplate.longTaskTimerSetByRecordRunnable("long.timer.test" , runnable);
    }

    @RequestMapping("/timed")
    public void TimedAnnotationTest(){
        exampleService.sleep5SecondsFunc();
    }
}
